// pages/my/my.js
import api from '@/utils/request'
import Dialog from '@vant/weapp/dialog/dialog';
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    unReadNum:0,
    tokenParams: {},
    userInfo: {},
    show: false,
    phone: '',
    showInfo: false,
    nickName: '',
    infoParams: {},
    url:'',
    bindShow:false,
    confirmShow:false,
    confirmDate:{},
    personTypeColumns:[]
    // actions: [
    //   { name: '获取手机号', color: '#07c160', openType: 'getPhoneNumber' },
    // ],
  },
  onGetUserInfo(e) {
    console.log(e.detail);
  },
  handleName() {
    this.setData({
      showInfo: true
    })
  },
  uploadFile() {
    const that = this
    wx.chooseMessageFile({
      count: 1, //能选择文件的数量
      type: 'image', //能选择文件的类型,我这里只允许上传文件.还有视频,图片,或者都可以
      success: (res) => {
        var size = res.tempFiles[0].size;
        var filename = res.tempFiles[0].name;
        var newfilename = filename + "";
        var fileTYpe = ['.png', '.jpg']
        const bollen = fileTYpe.some(item => {
          return newfilename.indexOf(item) > 0
        })
        if (!bollen) { //我还限制了文件的大小和具体文件类型
          wx.showToast({
            title: '支持.png，.jpg格式文件',
            icon: "none",
            duration: 2000,
            mask: true
          })
        } else {
          // 拿到本地路径将其作为参数上传
          console.log('shangchuan', res, filename);
          wx.uploadFile({
            url: `${app.globalData.host}` + '/file/upload', // 上传接口
            filePath: res.tempFiles[0].path,
            header: {
              Authorization: 'Bearer ' + wx.getStorageSync('Authorization'),
              "Content-Type": "multipart/form-data"
            },
            name: 'file',
            success: (res) => {
              const arr = that.data.path
              const arrer = that.data.name
              // this.setData({'formData.attachment':JSON.parse(res.data).data})
              // console.log('attachment',JSON.parse(res.data))
              wx.showToast({
                title: '上传附件成功',
              })
              api.post('/user/update', {
                avatarUrl: JSON.parse(res.data).data,
                nickName: this.data.userInfo.nickName
              }).then(res => {
                wx.showToast({
                  title: '修头像称成功',
                })
                this.setData({
                  showInfo: false,
                  nickName: ''
                })
                this.getUserInfo()
              })
            }
          })
        }
      }
    })
  },
  handleConfirm(e) {
    console.log(this.data.nickName)
    api.post('/user/update', {
      nickName: this.data.nickName,
      avatarUrl: this.data.userInfo.avatarUrl
    }).then(res => {
      wx.showToast({
        title: '修改昵称成功',
      })
      this.setData({
        showInfo: false,
        nickName: ''
      })
      this.getUserInfo()
    })
  },
  // 去完善个人信息
  toInfo() {
    if (!wx.getStorageSync('Authorization')) {
      wx.showToast({
        title: '未登录，请先登录',
        icon: 'error'
      })
      return
    }
    wx.navigateTo({
      url: '/subPackages/pages/info/info'
    })
  },

  async handleWxLogin() {
    wx.login({
      success: async (res) => {
        // 发送code临时登录凭证到后端
        await api.post('/user/code2session', {
          code: res.code
        }).then(res => {
          this.setData({
            'tokenParams.openId': res.openid
          })
        }).catch(err => {})
      }
    });
    // 获取token
    await wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: async (res) => {
        this.setData({
          'tokenParams.nickName': res.userInfo.nickName,
          'tokenParams.avatarUrl': res.userInfo.avatarUrl,
        })
        await api.post('/user/login', this.data.tokenParams).then(res => {
          wx.setStorageSync('Authorization', res.accessToken)
          app.routerList = [{
              name: "同心门户",
              icon: "home-o",
              url: "/pages/index/index",
            },
            {
              name: "同心阵地",
              icon: "chat-o",
              url: "/pages/service/service",
            }, {
              name: "同心风采",
              icon: "chat-o",
              url: "/pages/service/service",
            }, {
              name: "个人中心",
              icon: "chat-o",
              url: "/pages/my/my",
            }
          ]
          if(wx.getStorageSync('urlWithArgs')){
            wx.navigateTo({
              url: wx.getStorageSync('urlWithArgs'),
            })
          }
        }).catch(err => {})
        this.getUserInfo()
      }
    })
  },
  getUserInfo() {
    let data = {}
    api.post('/user/info').then(res => {
      data = res
      data.phone = res?.phone?.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
      wx.setStorageSync('userInfo', JSON.stringify(data))
      this.setData({
        userInfo: data
      })
    })
  },
  showPopup() {
    this.setData({
      show: true
    });
  },
  onClose() {
    this.setData({
      show: false,
      showInfo: false,
      bindShow:false,
      confirmShow:false
    });
  },
  handlePhone() {
    // this.setData({ show: true });
    // this.data.show = !this.data.show
    console.log(this.data.show, '-0-=0-0')
    api.post('/user/bind-phone', {
      phone: this.data.phone
    }).then(res => {
      // wx.setStorageSync('Authorization', res.accessToken)
      console.log(res, '------')
      this.setData({
        show: false
      })
      this.getUserInfo()
    }).catch(err => {})
  },
  handleOpneBindShow(){
    console.log(this.data.userInfo,'this.data.userInfo.roleType')
    if (!wx.getStorageSync('Authorization')) {
      wx.showToast({
        title: '未登录，请先登录',
        icon: 'error'
      })
      return
    } else if (!this.data.userInfo.phone) {
      wx.showToast({
        title: '未绑定手机号，请先绑定手机号',
        icon: 'error'
      })
      return
    }else if (this.data.userInfo.roleType=='admin') {
      wx.showToast({
        title: '账号已绑定',
        icon: 'none'
      })
      return
    }else if(this.data.userInfo.roleType=='united') {
      wx.showToast({
        title: '身份已确认',
        icon: 'none'
      })
      return
    }else if(!this.data.userInfo.roleType){
      this.setData({bindShow:true})
    }
  },
  handleSysPhone() {
    Dialog.confirm({
        title: '绑定手机号',
        selector: '#van-dialog',
        message: `确认绑定${this.data.userInfo.phone}吗？`,
      })
      .then(() => {
        // on confirm
        console.log('on confirm')
        api.post('/user/apply-bind').then(res => {
          console.log('-----', res)
          if (res) {
            this.getUserInfo()
            this.setData({bindShow:false})
          }
        })
      })
      .catch(() => {
        // on cancel
      });

  },
  confirmBind(){
    api.post('/user/confirm-bind').then(res=>{
      this.getUserInfo()
      this.onClose()
    })
  },
  getPersonType() {
    api.get('/dict/getByType?type=' + 'religious_personnel').then(res => {
      this.setData({
        personTypeColumns: res
      })
    })
  },
  handleIdentification() {
    api.post('/user/bindUserInfo').then(res=>{
      this.setData({
        confirmDate:res,
        confirmShow:true
      })
      this.data.personTypeColumns.map(val => {
        if (res?.personType == val.value) {
          this.setData({
            'confirmDate.personType': val.label
          })
        }
      })
    }).catch(err=>{
      if(err.code==777){
        wx.navigateTo({
          url: '/subPackages/pages/info/info',
        })
      }
    })
    // Dialog.confirm({
    //     title: '确认身份',
    //     selector: '#van-dialog',
    //     message: `确认绑定${this.data.userInfo.phone}吗？`,
    //   })
    //   .then(() => {
    //     // on confirm
    //     console.log('on confirm')
    //     api.post('/user/apply-bind').then(res => {
    //       console.log('-----', res)
    //       if (res) {
    //         this.getUserInfo()
    //       }
    //     })
    //   })
    //   .catch(() => {
    //     // on cancel
    //   });
  },
  getNumber() {
    api.get('/message/getUnreadCount').then(res => {
      if (res > 99) {
        this.setData({
          unReadNum: '99+'
        })
      } else {
        this.setData({
          unReadNum: res
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // console.log(options,'00000000000000000000000000000000000000000000000000000')
    // this.setData({url:options.url})
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      userInfo: JSON.parse(wx.getStorageSync('userInfo') || "{}")
    })
    this.getPersonType()
    // console.log(this.data.userInfo,'p-                   
    if(Object.keys(this.data.userInfo).length!==0){
      this.getUserInfo()
      this.getNumber()
    }
    if (typeof this.getTabBar == 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        // 这里的数字对应tabbar对应的索引
        selected: 2,
      });
    }
    // this.getTabBar().setData({
    //   // 这里的数字对应tabbar对应的索引
    //   selected: 4,
    // });
    // console.log(this.getTabBar.data,'this.getTabBar')
    // if (typeof this.getTabBar === "function" && this.getTabBar()) {
    //   console.log('====')
    //   this.getTabBar().setData({
    //     // 这里的数字对应tabbar对应的索引
    //     selected: 4,
    //   });
    // }
  },
  toMyList({
    currentTarget
  }) {
    if (!wx.getStorageSync('Authorization')) {
      wx.showToast({
        title: '未登录，请先登录',
        icon: 'error'
      })
      return
    }
    if(currentTarget.dataset.type=='task'){
      wx.navigateTo({
        url:"/subPackages/pages/work/work"
      })
    }else{
      wx.navigateTo({
        url: '/subPackages/pages/myList/myList?type=' + currentTarget.dataset.type,
      })
    }
  },

  logout() {
    wx.clearStorageSync()
    this.setData({
      userInfo: {},
      unReadNum:0
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})